const fetch = require('node-fetch');

/**
 * AI 内容审核插件（支持 OpenAI Moderation 格式，可自定义服务和模型）
 * @param {Object} options
 * @param {string} options.apiKey - OpenAI API Key 或自定义服务鉴权
 * @param {string} [options.endpoint] - 审核接口地址，默认 https://api.openai.com/v1/moderations
 * @param {string} [options.model] - 审核使用的模型名，默认 omni-moderation-latest
 */
module.exports = function({ apiKey, endpoint = 'https://api.openai.com/v1/moderations', model = 'omni-moderation-latest' }) {
  if (!apiKey) {
    return {};
  }

  return {
    hooks: {
      async preSave(data) {
        const { userInfo } = this.ctx.state;
        const isAdmin = userInfo.type === 'administrator';
        // ignore admin comment
        if (isAdmin) {
          return;
        }

        try {
          // 构造请求体
          const body = {
            model,
            input: data.comment,
          };

          // 请求审核接口
          const resp = await fetch(endpoint, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${apiKey}`,
            },
            body: JSON.stringify(body),
          });

          const result = await resp.json();

          // 判断结果结构
          const moderation = result?.results?.[0];
          if (typeof moderation?.flagged !== 'boolean' || !moderation?.categories) {
            throw new Error('Moderation result missing flagged or categories. Raw response: ' + JSON.stringify(result));
          }

          if (moderation.flagged === false) {
            data.status = 'approved';
            return;
          }

          // flagged 为 true，分析 categories
          const categories = moderation.categories;

          // spam 类型单独处理
          const isSpam = categories.spam === true;
          const otherCategoriesViolated = Object.entries(categories)
            .some(([key, value]) => key !== 'spam' && value === true);

          if (otherCategoriesViolated) {
            data.status = 'spam';
          } else if (isSpam) {
            data.status = 'waiting';
          } else {
            data.status = 'waiting';
          }
        } catch (e) {
          console.log(e);
          data.status = 'waiting';
        }
      },
    },
  };
}